var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
var constants = require("../utils/constants");
const { checkProperty, checkAuth } = require("../utils/utils");
const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_FAVOURITE_LIST";
const viewName = "JIANGDU_FAVOURITE_VIEW";
const jwt = require("jsonwebtoken");
let log = require("cf-nodejs-logging-support");
const { POLICYTABLE } = require("../utils/constants");
log.setLoggingLevel("info");

var test =
    "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuB7GGI+UvP8G/dbzqXwAm5Wo8dBcsdag+00GeRiuRcR4/0dl0g2d8C3X4/Z6CfVuj4fnDznNNJAliawF6BEoCQp7GEkdSCj8xCou1RtGdOTHTaIIfPIz5GmQ9X0J//JlWButHiP2jtsuZXYIHQoAGtdW798Fxak8ggzrfuN+c9NTGdmQs7VgOwJp+8StnvUhcQydx4918hxOg+udKlokN5oZ/ri4lLGuOT2+9XwVTpvwHeNZDFLNaaKXdc1C5yqQ+3vLM837LA6KhkgWnAXAsGDqPTyWkPZ1WqobruV2wotje3hjmuMkBp7Jhz9ymwOBkRxOLhvskGKRqkokdWTHPQIDAQAB\n-----END PUBLIC KEY-----";
function authenticateToken(req, res, next) {
    const authHeader = req.headers["authorization"];
    const token = authHeader && authHeader.split(" ")[1];

    if (token == null) return res.sendStatus(401);

    jwt.verify(token, test, { algorithms: ["RS256"] }, (err, user) => {
        if (err) return res.sendStatus(403);

        req.user = user;

        next();
    });
}

router.get("/", function (req, res, next) {
    // #swagger.tags = ['收藏']
    // #swagger.summary = '获得我的收藏。需要jwttoken'
    // #swagger.description = '获得我的收藏。需要jwttoken.返回所有的我的收藏'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    /* #swagger.parameters['type'] = {
          description: "PO||AS||TA||TE||FI",
          required: false,
    } */
    //authenticateToken(req, res, next)

    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    const payload = {
        USER_ID_USER_ID: user.user_id,
    };
    const { type } = req.query;
    payload.type = type;
    getFavoriteList(payload)
        .then((result) => {
            res.send(result);
            return result;
        })
        .catch((err) => {
            // log.error(err);
            res.status(500).send(err);
        });
});

async function getFavoriteList(payload) {
    const sqlConn = new ohana(tableName);

    let sqlText =
        "select * from " +
        viewName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "'";
    if (payload.type) {
        sqlText += " and TYPE = '" + payload.type + "'";
    }
    const result = await sqlConn.raw(sqlText);
    return result;
}

router.get("/isDuplicate", function (req, res, next) {
    // #swagger.tags = ['收藏']
    // #swagger.summary = '检查是否已经收藏'
    // #swagger.description = '检查是否已经收藏 返回true/false'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */

    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    const payload = {
        USER_ID_USER_ID: user.user_id,
    };
    const { FAVOURITE_ID } = req.query;
    payload.FAVOURITE_ID = FAVOURITE_ID;
    isDuplicate(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function isDuplicate(body) {
    const sqlConn = new ohana(tableName);
    const result = await sqlConn.find(body);
    if (result.length > 0) {
        return true;
    } else {
        return false;
    }
}

router.post("/", function (req, res, next) {
    // #swagger.tags = ['收藏']
    // #swagger.summary = '添加我的收藏，重复插入会直接更新'
    // #swagger.description = '添加我的收藏'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/favorite_add"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }

    const { data } = req.body;
    data.FAVOURITE_LIST_ID = uunewid.v4();
    data.USER_ID_USER_ID = user.user_id;

    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function insertData(body) {
    const user = new ohana(tableName);
    const policyConn =new ohana(POLICYTABLE)
    const condition = {
        USER_ID_USER_ID: body.USER_ID_USER_ID,
        FAVOURITE_ID: body.FAVOURITE_ID,
    };
    // console.log(body);
    const result = await user.updateOrCreate(condition, body);
    if(body.TYPE=='PO'){
        let updatePolicy=await policyConn.findOne({POLICY_ID:body.FAVOURITE_ID});
        updatePolicy[0].POPULARITY=updatePolicy[0].POPULARITY+1;
        policyConn.update({POLICY_ID:body.FAVOURITE_ID},{POPULARITY:updatePolicy[0].POPULARITY})
    }
    return result;
}

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['收藏']
    // #swagger.summary = '删除收藏'
    // #swagger.description = '删除单个我的收藏:需要FAVOURITE_ID。删除该用户所有收藏type 为all 。删除某个类型的收藏，type为该类型的值PO或者AS'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/favorite_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    const user = checkAuth(req.user, constants.BASICAUTH);
    data.USER_ID_USER_ID = user.user_id;
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    deleteFavorite(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
                return;
            } else {
                res.send({ message: "找不到对应条目", code: "-1" });
                return;
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});
async function deleteFavorite(data) {
    const sqlConn = new ohana(tableName);
    if (data.type) {
        sqlText =
            'delete from "' +
            tableName +
            "\" where USER_ID_USER_ID = '" +
            data.USER_ID_USER_ID +
            "'";
        if (data.type != "all") {
            sqlText += " and TYPE = '" + data.type + "'";
        }
    } else {
        sqlText =
            'delete from "' +
            tableName +
            "\" where USER_ID_USER_ID = '" +
            data.USER_ID_USER_ID +
            "' and FAVOURITE_ID = '" +
            data.FAVOURITE_ID +
            "'";
    }
    const result = await sqlConn.raw(sqlText);
    // if(data.TYPE=='PO'){
        const policyConn =new ohana(POLICYTABLE);
        let updatePolicy=await policyConn.findOne({POLICY_ID:data.FAVOURITE_ID});
        if(updatePolicy.length>0)
        {
            updatePolicy[0].POPULARITY=updatePolicy[0].POPULARITY-1;
            policyConn.update({POLICY_ID:data.FAVOURITE_ID},{POPULARITY:updatePolicy[0].POPULARITY})
        }
    // }
    return result;
}

router.get("/count", function (req, res, next) {
    // #swagger.tags = ['收藏']
    // #swagger.summary = '获得我的收藏条目数据。需要jwttoken'
    // #swagger.description = '获得我的收藏条目数据。需要jwttoken.返回所有的我的收藏'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    const payload = {
        USER_ID_USER_ID: user.user_id,
    };
    countFavoriteList(payload)
        .then((result) => {
            res.send(result);
            return result;
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function countFavoriteList(payload) {
    const sqlConn = new ohana(tableName);
    let result = [];
    let allPromise = []
    var sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "'";
    // var resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    // result.push({
    //     type: "total",
    //     count: resultTotal[0].COUNT,
    // });
    sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "' and TYPE = 'PO'";
    // resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    // result.push({
    //     type: "PO",
    //     count: resultTotal[0].COUNT,
    // });
    sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "' and TYPE = 'TA'";
    // resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    // result.push({
    //     type: "TA",
    //     count: resultTotal[0].COUNT,
    // });
    sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "' and TYPE = 'TE'";
    // resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    // result.push({
    //     type: "TE",
    //     count: resultTotal[0].COUNT,
    // });
    sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "' and TYPE = 'AS'";
    // resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    // result.push({
    //     type: "AS",
    //     count: resultTotal[0].COUNT,
    // });
    sqlText =
        "select count(*) as count from " +
        tableName +
        " where USER_ID_USER_ID ='" +
        payload.USER_ID_USER_ID +
        "' and TYPE = 'FI'";
    resultTotal = await sqlConn.raw(sqlText);
    allPromise.push(sqlConn.raw(sqlText))
    let tmpResult = await Promise.all([...allPromise])
    let types  = ["total","PO","TA","TE","AS","FI"]
    for (let index = 0; index < tmpResult.length; index++) {
        const element = tmpResult[index];
        result.push({
            type: types[index],
            count: element[0].COUNT,
        });
    }
    // for (num of tmpResult){
    //     result.push({
    //         type: "FI",
    //         count: num[0].COUNT,
    //     });
    // }
    return result;
}

module.exports = router;
